<!-- Bot Read Me -->
<!-- Author: Edwin -->
<template>
  <el-dialog style="width: 100%;height: 100%"
             :withHeader="false"
             width="951px"
             :append-to-body="true"
             :visible.sync="visible"
             @close="canceldialog">
    <!--<div slot="header" class="clearfix">
              <i class="el-icon-close" @click="visible = false"></i>
              <el-button @click="saveForm(false)" style="float: right; padding: 3px 5px" type="text">{{ $t('custom.save') }}</el-button>
              <el-button @click="saveForm(true)" style="float: right; padding: 3px 0" type="text">{{ $t('custom.apply') }}</el-button>

          </div>-->
    <div class='bot-read-me'>
      <el-card shadow="never">
        <div class="bot-read-me-introduce">
          <div class="bot-read-me-introduce-image">
            <el-image :src="`${$ossLink}/app/bot/bot_icon_large.png`">
              <div slot="error"
                   class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </div>
          <div class="bot-read-me-introduce-content">
            <div class="bot-read-me-introduce-content-title">
              {{dataForm.name}}
              <el-tag size="small">Free</el-tag>
            </div>
            <div class="bot-read-me-introduce-content-tips">
              {{dataForm.description}}
            </div>
            <div class="bot-read-me-introduce-content-other">
              <div class="bot-read-me-introduce-content-other-update-time">{{$t('custom.bots.updatedDate')}}{{dataForm.updateTime || ''}}</div>
              <div class="bot-read-me-introduce-content-other-version">{{$t('custom.bots.version')}}{{dataForm.version || ''}}</div>
              <div class="bot-read-me-introduce-content-other-author">{{$t('custom.bots.author')}}{{dataForm.auth || ''}}</div>
            </div>
          </div>
          <div class="bot-read-me-introduce-button">
          </div>
        </div>
      </el-card>
      <!--  <el-card>
        <div class="bot-read-me-content">
          <el-form>
            <el-form-item>
              <el-radio v-model="dataForm.toType" :label="1">{{$t('custom.bots.sendtouser')}}</el-radio>
              <el-radio v-model="dataForm.toType" :label="2">{{$t('custom.bots.sendtochannel')}}</el-radio>
            </el-form-item>
          <el-form-item v-if="dataForm.toType == 2">
              <el-select v-model="dataForm.toId"
                        default-first-option
                        filterable
                        :placeholder="$t('custom.bots.channel')">
                <el-option v-for="item in channelList"
                            :key="item.channelId"
                            :label="item.displayName"
                            :value="item.channelId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </el-card>-->
      <el-card shadow="never">
        <div class="bot-read-me-content">
          <el-form :model="dataForm"
                   label-position="top"
                   ref="dataForm"
                   @keyup.enter.native="dataFormSubmitHandle()"
                   label-width="120px">
            <template v-for="(fc,i) in watchActiveItem"
                      :label="fc.label">
              <el-form-item :key="i"
                            v-if="fc.type === 'switch'">
                <el-switch v-model="dataForm.paramsValue[fc.text]"
                           :active-text="fc.label"
                           :disabled="!dataForm.enable">
                </el-switch>
              </el-form-item>
              <el-form-item :key="i"
                            :label="fc.label"
                            v-else-if="fc.type === 'text'">
                <el-input v-model="dataForm.paramsValue[fc.text]"
                          :counter="fc.counter"
                          :rules="fc.rules"
                          :label="fc.label"
                          persistent-hint
                          :placeholder="fc.hint"
                          required></el-input>
              </el-form-item>
              <el-form-item :key="i"
                            :label="fc.label"
                            v-else-if="fc.type === 'textarea'">
                <quill-editor style="padding: 10px 0;"
                              :name="fc.id"
                              ref="myTextEditor"
                              :hint="fc.hint"
                              :placeholder="fc.placeholder"
                              :label="fc.label"
                              v-model="dataForm.paramsValue[fc.text]"
                              :options="editorOption"></quill-editor>
                <el-tooltip :open-delay="1000" class="item"
                            effect="dark"
                            :content="$t('custom.bots.load_default_tips')"
                            placement="top">
                  <el-button type="text"
                             @click="loadDefault(fc.text)">{{ $t('custom.bots.load_default') }}</el-button>
                </el-tooltip>
              </el-form-item>
              <el-form-item :key="i"
                            :label="fc.label"
                            v-else-if="fc.type === 'select'">
                <div v-if="getSelectDataLists(fc)"></div>
                <el-select v-model="dataForm.paramsValue[fc.text]"
                           filterable
                           clearable
                           :placeholder="fc.placeholder"
                           default-first-option>
                  <el-option v-for="(o,ii) in selectDataObj[`${fc.text}ListsOrigin`]"
                             :key="ii"
                             :value="o[fc.fieldValue]"
                             :label="o[fc.fieldLabel]"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item :key="i"
                            :label="fc.label"
                            v-else-if="fc.type === 'customized-select'">
                <div v-if="getSelectDataLists(fc)"></div>
                <el-select v-model="dataForm.paramsValue[fc.text]"
                           filterable
                           clearable
                           :placeholder="fc.placeholder"
                           default-first-option>
                  <el-option v-for="its in fc.selectList"
                             :key="its.value"
                             :label="its.label"
                             :value="its.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item :key="i"
                            :label="fc.label"
                            v-else-if="fc.type === 'autocomplete'">
                <div v-if="getSelectDataLists(fc)"></div>
                <el-select v-model="dataForm.paramsValue[fc.text]"
                           filterable
                           clearable
                           multiple
                           :placeholder="fc.placeholder"
                           collapse-tags
                           default-first-option>
                  <el-option v-for="(o,ii) in selectDataObj[`${fc.text}ListsOrigin`]"
                             :key="ii"
                             :value="o[fc.fieldValue]"
                             :label="o[fc.fieldLabel]"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item :key="i"
                            :label="fc.label"
                            v-else-if="fc.type === 'customized-autocomplete'">
                <div v-if="getSelectDataLists(fc)"></div>
                <el-select v-model="dataForm.paramsValue[fc.text]"
                           filterable
                           clearable
                           multiple
                           collapse-tags
                           :placeholder="fc.placeholder"
                           default-first-option>
                  <el-option v-for="its in fc.selectList"
                             :key="its.value"
                             :label="its.label"
                             :value="its.value"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-form>
        </div>
      </el-card>
    </div>
    <template slot="footer">
      <el-button size="small"
                 @click="canceldialog">{{ $t('cancel') }}</el-button>
      <template v-if="$hasPermission('sys:bots:edit')">
        <el-button size="small"
                   type="primary"
                   @click="dataFormSubmitHandle(true)">{{ $t('custom.bots.apply') }}</el-button>
        <el-button size="small"
                   type="primary"
                   @click="dataFormSubmitHandle(false)">{{ $t('custom.bots.saveandclose') }}</el-button>
      </template>
    </template>
  </el-dialog>
</template>
<script>
import store from '@/store'
export default {

  data () {
    return {
      visible: false,
      header: false,
      dataForm: {
        id: '',
        tenantCode: '',
        name: '',
        paramsValue: '',
        context: '',
        scope: '',
        triggerEvent: '',
        enable: false,
        applyTenant: false,
        version: '',
        paramsJson: '',
        description: '',
        sysParamsJson: '',
        sysParamsValue: '',
        toType: 1,
        toId: null
      },
      channelList: [],
      editorOption: {
        name: '232',
        modules: {
          toolbar: [
            ['code-block'],
            [{ 'direction': 'rtl' }],
            ['bold', 'italic', 'underline', 'strike'],
            [{ 'color': [] }],
            [{ 'background': [] }],
            [{ 'header': 1 }, { 'header': 2 }],
            [{ 'script': 'sub' }, { 'script': 'super' }],
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            [{ 'indent': '-1' }, { 'indent': '+1' }],
            [{ 'font': ['sans-serif', 'monospace', 'serif'] }],
            [{ 'size': ['small', false, 'large', 'huge'] }],
            [{ 'align': [] }],
            ['link'],
            ['clean']
          ]
        },
        theme: 'snow',
        placeholder: ''
      },
      selectDataObj: {},
      interfaceNoDataCount: 0
    }
  },
  created () {
    this.getChannelList()
  },
  computed: {
    watchActiveItem () {
      try {
        return this.dataForm.paramsJson && JSON.parse(this.dataForm.paramsJson).fields
      } catch (e) {
        return []
      }
    }
  },

  watch: {
    watchActiveItem: {
      handler: function (newValue, oldValue) {
        if (newValue && newValue !== oldValue) {
          const fields = newValue && newValue.fields ? newValue.fields : []
          for (let i = 0; i < fields.length; i++) {
            try {
              if (this.dataForm.paramsValue[fields[i].text] === undefined && fields[i].defaultValue) {
                this.$set(this.dataForm.paramsValue, [fields[i].text], fields[i].defaultValue)
              }
            } catch (e) {
            }
          }
        }
      },
      deep: true
    },
    visible (val) {
      if (!val) {
        this.$root.eventBus.$emit('bus:tag-refresh')
      }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        // this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          var loginAs = store.state.app.isSwitchTenant ? store.state.app.isSwitchTenant : sessionStorage.getItem('isSwitchTenant') || 0
          this.$interface.um.poststatRouteAPI({ url: `/bot-${this.dataForm.id}?pageid=botdetail&botId=${this.dataForm.id}&loginAs=${loginAs}` })
          this.getInfo()
        }
      })
    },
    getInfo () {
      this.$interface.bots.getTenantScriptInfoApi(this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data
          }

          if (!this.dataForm.toType) {
            this.dataForm.toType = 1
          }

          if (this.dataForm.paramsJson === {}) {
            this.dataForm.paramsJson = this.dataForm.sysParamsJson
          }
        }).catch(() => { })
    },
    dataFormSubmitHandle (isVisible) {
      if (this.dataForm.paramsValue.send === false) {
        this.dataForm.paramsValue.sendEscalation = false
      }
      const params = {
        id: this.dataForm.id,
        version: this.dataForm.version,
        paramsValue: this.dataForm.paramsValue,
        toType: this.dataForm.toType,
        toId: this.dataForm.toType === 1 ? '' : this.dataForm.toId
      }
      this.$interface.bots.updateTenantScriptApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$emit('refreshDataList')
          this.visible = isVisible
        }).catch(() => { })
    },
    loadDefault (text) {
      this.dataForm.paramsValue[text] = this.dataForm.sysParamsValue[text]
    },
    canceldialog () {
      this.visible = false
      this.$emit('refreshDataList')
    },
    getChannelList () {
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }

      this.$interface.botStore.getChannelList(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.channelList = res.data
        })
        .catch(() => { })
    },
    getSelectDataLists (item) {
      if (this.interfaceNoDataCount > 10) {
        return false
      }
      if (item.interfaceUrl && this.hasSelectData(item)) {
        return false
      }
      const url = item.interfaceUrl
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      this.$interface.clientReport.getBoardListForBotApi(url, params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data) {
            this.selectDataObj[`${item.text}ListsOrigin`] = res.data
            this.selectDataObj = Object.assign({}, this.selectDataObj)
          }
          // Example:
          // {
          //   "fields": [
          //     {
          //        "text":"edwinTestSelect",
          //        "label":"Edwin Test",
          //        "type":"autocomplete",
          //        "defaultValue": null,
          //        "interfaceUrl": "/web/tasks/tennant_cw_board/findBoardList",
          //        "fieldLabel": "name",
          //        "fieldValue": "name"
          //     }
          //   ]
          // }
        }).catch(() => { })
    },
    hasSelectData (item) {
      try {
        if (this.selectDataObj[`${item.text}ListsOrigin`] && this.selectDataObj[`${item.text}ListsOrigin`].length > 0) {
          this.interfaceNoDataCount = 0
          return true
        } else {
          this.interfaceNoDataCount++
          return false
        }
      } catch (error) {
        this.interfaceNoDataCount++
        return false
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import "src/views/modules/mspbots/bots/my-bots/my-bot";
</style>
